package servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import pojo.*;
import dao.OrderDao;
import dao.impl.OrderDaoImpl;

public class BuyServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	 Logger logger=Logger.getLogger(BuyServlet.class);  
    private OrderDao dao;
    public BuyServlet() {
        super();
        dao=new OrderDaoImpl();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Map<String, OrderInfo> carts=(Map<String, OrderInfo>)request.getSession().getAttribute("cart");
		if(null==carts){
			request.getRequestDispatcher("store").forward(request, response);
			return;
		}
		List<Order> orders=new ArrayList<>();
		for(String s:carts.keySet())
		{
			orders.add(toOrder(carts.get(s)));
		}
		int m=dao.addOrderList(orders);
		if(m>0)
		{
			logger.info(((User)request.getSession().getAttribute("user")).getName()+"buy Success");
			request.getSession().removeAttribute("cart");
		}
		request.getRequestDispatcher("cart.jsp").forward(request, response);
	}

	private Order toOrder(OrderInfo orderInfo) {
		Order order=new Order();
		order.setB_id(orderInfo.getBidString());
		order.setNumber(orderInfo.getCount());
		order.setU_id(orderInfo.getUidString());
		return order;
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
